<?php

/**
 * po actions.
 *
 * @package    student_manager
 * @subpackage po
 * @author     Your name here
 * @version    SVN: $Id: actions.class.php 2288 2006-10-02 15:22:13Z fabien $
 */
class poActions extends autopoActions
{

public function executeViewNotes(){
    $this->getResponse()->setTitle('WMS-ViewNotes-PO');
    $this->po = $this->getPOOrCreate();
    $this->labels = $this->getLabels();
}

public function executeRevise(){
    $this->getResponse()->setTitle('WMS-Revise-PO-Id-'.$this->getRequestParameter('id'));
    $Id = $this->getRequestParameter('id');
    $po = POPeer::retrieveByPK($Id);
    if (!$po){
        $this->getRequest()->setError('revise', 'This PO is not available!');
        $this->forward('po', 'list');
    }
    if ($po->getApprovalstatus() != CommonValues::$gMRApprovalStatus['key']['Approved']) {
        $this->getRequest()->setError('revise', 'Could not revise this PO!');
        $this->forward('po', 'list');
    }
    $this->redirect('po/create?prepare_revise_Id='.$Id);
}
public function executeChangeNumber(){
    $this->getResponse()->setTitle('WMS-Change-No-PO-Id-'.$this->getRequestParameter('id'));
	$id = $this->getRequestParameter('id');
    if ($this->getRequest()->isMethod('post')){    	
    	$no = $this->getRequestParameter('no');
    	if ($id && $no){
    		$obj = POPeer::retrieveByPK($id);
    		if ($obj){
	    		$obj->setPono($no);
	    		$obj->save();
	    		$this->getUser()->setFlash('notice',  'change PO number successfully!');
	    		return $this->redirect("po/list?id=$id");
    		}
    	}
    }
    
    $obj = POPeer::retrieveByPK($id);
    $this->no = $obj->getPono();
    $this->id = $id;
}
//HAM CHANGE DATE
public function executeChangeDate()
{
    if (!$this->getUser()->hasCredential('EDIT_PO'))
    {
        $this->getUser()->setFlash('notice',  'You dont have permission to edit PO!');
        return $this->redirect("po/list?id=$id");
    }
     
    $id = $this->getRequestParameter('id');    
    $obj = POPeer::retrieveByPK($id);
    if (!$obj)
    {
        $this->getUser()->setFlash('notice',  'PO is not exist!');
        return $this->redirect("po/list");
    }
    if ($obj->getApprovalstatus() != CommonValues::$gMRApprovalStatus['key']['Approved'])
    {
        $this->getUser()->setFlash('notice',  'This PO is not yet published!');
        return $this->redirect("po/list?id=$id");
    }
    
    $this->getResponse()->setTitle('WMS-PO-Change-Date-'.$obj->getPono());
     //Lay ve Id cua Tally In
  
    if ($this->getRequest()->isMethod('post'))
    { 
        //Lay ve ngay can thay doi
    	$date = $this->getRequestParameter('changedate');
        
    	if ($date)
        {           
            $obj->setCreatedAt($date);
            $obj->save();   
             $this->getUser()->setFlash('notice',  'Change date of '.$obj->getPono().' successfully!');
            return $this->redirect("po/list?id=$id");
        }
    }
    $this->changedate = $obj->getCreatedAt();     
    $this->id = $id;
}
public function executeConfig(){
            $this->getResponse()->setTitle('WMS-Config-PO');
		if ($this->getRequest()->isMethod('post')){
			$contactperson = $this->getRequestParameter('contactperson');
			$docrequire = $this->getRequestParameter('docrequire');
                        $printTemplate = $this->getRequestParameter('printTemplate');
			if ($contactperson && $docrequire){
				$c = new Criteria();
				$c->add(MyConfigPeer::IDS, "IDS_PO_CONTACTPERSON");
				$config = MyConfigPeer::doSelectOne($c);
				$config->setDescription($contactperson);
				$config->save();
				
				$c = new Criteria();
				$c->add(MyConfigPeer::IDS, "IDS_PO_DOCUMENTREQUIRE");
				$config = MyConfigPeer::doSelectOne($c);
				$config->setDescription($docrequire);
				$config->save();

				$c = new Criteria();
				$c->add(MyConfigPeer::IDS, "IDS_PO_PRINT_TEMPLATE");
				$config = MyConfigPeer::doSelectOne($c);
				$config->setDescription($printTemplate);
				$config->save();
				
				$this->getUser()->setFlash('notice', 'change successfully!');
			}
		}
		$c = new Criteria();
		$c->add(MyConfigPeer::IDS, "IDS_PO_CONTACTPERSON");
		$config = MyConfigPeer::doSelectOne($c);
		if ($config)
		$this->contactperson = $config->getDescription();
		
		$c = new Criteria();
		$c->add(MyConfigPeer::IDS, "IDS_PO_DOCUMENTREQUIRE");
		$config = MyConfigPeer::doSelectOne($c);
		if ($config)
		$this->docrequire = $config->getDescription();

		$c = new Criteria();
		$c->add(MyConfigPeer::IDS, "IDS_PO_PRINT_TEMPLATE");
		$config = MyConfigPeer::doSelectOne($c);
                if ($config)
		$this->printTemplate = $config->getDescription();
	}
public function executeRateCurrencyConfig()
{
    $this->usdvnd = "";		
    $this->usdsgd = "";
    if ($this->getRequest()->isMethod('post')){
        $usdvnd = $this->getRequestParameter('usdvnd');
        $usdsgd= $this->getRequestParameter('usdsgd');        
        if ($usdvnd)
        {
            $c = new Criteria();
            $c->add(MyConfigPeer::IDS, 'USDVND');
            $configvnd = MyConfigPeer::doSelectOne($c);
            if (!$configvnd)
            {
                $configvnd = new MyConfig();
                $configvnd->setDescription($usdvnd);
                $configvnd->setIds('USDVND');
                $configvnd->save();				
            }
            else
            {
                $configvnd->setDescription($usdvnd);               
                $configvnd->save();                
            }
        }
        if ($usdsgd)
        {
            $c = new Criteria();
            $c->add(MyConfigPeer::IDS, 'USDSGD');
            $configsgd = MyConfigPeer::doSelectOne($c);
            if (!$configsgd)
            {
                $configsgd = new MyConfig();
                $configsgd->setDescription($usdsgd);
                $configsgd->setIds('USDSGD');
                $configsgd->save();				
            }
            else
            {
                $configsgd->setDescription($usdsgd);               
                $configsgd->save(); 
            }

        }
        $this->getUser()->setFlash('notice', 'save exchange rate successfully!');
    }
    $c = new Criteria();
    $c->add(MyConfigPeer::IDS, "USDVND");
    $config = MyConfigPeer::doSelectOne($c);
    if ($config)
        $this->usdvnd = $config->getDescription();		
    
    $c = new Criteria();
    $c->add(MyConfigPeer::IDS, "USDSGD");
    $config = MyConfigPeer::doSelectOne($c);
    if ($config)
        $this->usdsgd = $config->getDescription();
    
}
public function executeResolveRVMR() {
    $this->getResponse()->setTitle('WMS-Resolve-Rvmr');

    $module ="";
    if ($this->getRequestParameter('mr_id'))    {
        $id = $this->getRequestParameter('mr_id');
        $mr = MRPeer::retrieveByPK($id);
        $module = 'MR';
        if (!$mr)
            $this->redirect('main/showDashboard');
    }
    
    if ($this->getRequestParameter('mr2_id'))    {
        $id = $this->getRequestParameter('mr2_id');
        $mr = MR2Peer::retrieveByPK($id);
        $module = 'MRSUB';
        if (!$mr)
            $this->redirect('main/showDashboard');
    }
    
    if ($this->getRequestParameter('mr3_id'))    {
        $id = $this->getRequestParameter('mr3_id');
        $mr = MR3Peer::retrieveByPK($id);
        $module = 'MRRAW';
        if (!$mr)
            $this->redirect('main/showDashboard');
    }
    
    $this->mr = $mr;
    $this->module = $module;
}

public function executeResolve() {
    $this->getResponse()->setTitle('WMS-Resolve-MR-Mod-'.$this->getRequestParameter('mod'));
    
    $module = $this->getRequestParameter('mod');
    if ($module=='MR')        
        $mr = MRPeer::retrieveByPK($this->getRequestParameter('mr_id'));
    elseif ($module=='MRSUB')
        $mr = MR2Peer::retrieveByPK($this->getRequestParameter('mr_id'));
    else $mr = MR3Peer::retrieveByPK($this->getRequestParameter('mr_id'));
    
    if (!$mr) return;
    
    $c = new Criteria();
    $c->add(POPeer::MRNO, $mr->getReviseId());
    if ($module =='MR')
       $c->add(POPeer::COMPCATEGORY, CommonValues::$gCompCategory['key']['Main Component']);
   elseif ($module == 'MRSUB')
       $c->add(POPeer::COMPCATEGORY, CommonValues::$gCompCategory['key']['Sub Component']);
   else $c->add(POPeer::COMPCATEGORY, CommonValues::$gCompCategory['key']['Raw Material']);

   $c->addOr(POPeer::APPROVALSTATUS, CommonValues::$gMRApprovalStatus['key']['Approved']);
   $c->addOr(POPeer::APPROVALSTATUS, CommonValues::$gMRApprovalStatus['key']['Initial']);
   $c->addOr(POPeer::APPROVALSTATUS, CommonValues::$gMRApprovalStatus['key']['Waiting for approval']);
    $polist = POPeer::doSelect($c);


    $rowIds = $this->getRequestParameter('rowIds');

    $MRCompgroupId = $mr->getComponentgroupId();
    
    if ($polist && count($polist)){
        foreach ($polist as $po){
            $action = $this->getRequestParameter('action'.$po->getId());
            //keep
            if ($action==0){                
                $po->setMrno($mr->getId());
                $po->save();
            }
            //revise
            elseif ($action==1){
                $po->setMrno($mr->getId());                
                $POcompsqty = $this->getRequestParameter('comps'.$po->getId());
                
                $compgroup = new ComponentGroup();
                $compgroup->setType(1);
                $compgroup->save();

                $POCompgroupIdOld = $po->getComponentgroupId();
                $po->setComponentgroupId($compgroup->getId());
                $po->save();

                $bFullReceived = true;
                $bPartialReceived = false;
                
                for ($i =0; $i < count($rowIds); $i++){
                    $compId = $rowIds[$i];
                    if ($POcompsqty[$i] >= 0) {
                        
                        $c = new Criteria();
                        $c->add(ComponentsPeer::COMPONENTGROUP_ID, $POCompgroupIdOld);
                        $c->add(ComponentsPeer::COMPONENT_ID, $compId);
                        $POcompsOld = ComponentsPeer::doSelectOne($c);

                        $c = new Criteria();
                        $c->add(ComponentsPeer::COMPONENTGROUP_ID, $MRCompgroupId);
                        $c->add(ComponentsPeer::COMPONENT_ID, $compId);
                        $MRComps = ComponentsPeer::doSelectOne($c);

                        $c = new Criteria();
                        $c->add(WarehousePeer::COMPONENT_ID, $compId);
                        $warehouse = WarehousePeer::doSelectOne($c);

                        //get old comps
                        if (!$POcompsOld){
                            $POcompsOld = new Components();
                            $POcompsOld->setQty1(0);
                        }
                        $POcomps =$POcompsOld->copy();

                        $POcomps->setComponentId($compId);
                        $POcomps->setComponentgroupId($compgroup->getId());

                        if ($MRComps){
                            $MRComps->setQty4($MRComps->getQty4() - $POcompsqty[$i] + $POcompsOld->getQty1());
                            $MRComps->save();
                        }
                        $POcomps->setQty4($POcomps->getQty4() +  $POcompsqty[$i] - $POcompsOld->getQty1());

                        if ($warehouse){
                            $warehouse->setQtyordered($warehouse->getQtyordered() + $POcompsqty[$i] - $POcompsOld->getQty1());
                            $warehouse->save();
                        }

                        $POcomps->setQty1($POcompsqty[$i]);

                        //neu =0 tuc la muon xoa
                        if ($POcomps->getQty1() > 0){
                            $POcomps->save();

                            if ($POcomps->getQty4() > 0){
                                $bFullReceived = false;
                                if ($POcomps->getQty4() < $POcomps->getQty1())
                                        $bPartialReceived = true;
                            }
                        }
                                
                    }
                }
                if ($bFullReceived){
                    $po->setReceivedstatus(CommonValues::$gPOReceivedStatus['key']['Fully Received']);
                    $po->setReceiveddate(date('Y-m-d'));
                }
                elseif ($bPartialReceived)
                    $po->setReceivedstatus(CommonValues::$gPOReceivedStatus['key']['Partially Received']);
                elseif ($po->getApprovalstatus() == CommonValues::$gMRApprovalStatus['key']['Initial'] ||
                $po->getApprovalstatus() == CommonValues::$gMRApprovalStatus['key']['Waiting for approval'])
                    $po->setReceivedstatus(CommonValues::$gPOReceivedStatus['key']['Initial']);
                else $po->setReceivedstatus(CommonValues::$gPOReceivedStatus['key']['In progress']);
            
                $po->save();
            }
            //delete
            elseif ($action==2){
                $po->setApprovalstatus(CommonValues::$gMRApprovalStatus['key']['Cancel']);
                $po->setReceivedstatus(CommonValues::$gPOReceivedStatus['key']['Cancel']);
                $po->save();

                $compgroupIdOld = $po->getComponentgroupId();
                $c = new Criteria();
                $c->add(ComponentsPeer::COMPONENTGROUP_ID, $compgroupIdOld);
                $compslist = ComponentsPeer::doSelect($c);

                foreach($compslist as $comps) {
                    $c = new Criteria();
                    $c->add(ComponentsPeer::COMPONENTGROUP_ID, $MRCompgroupId);
                    $c->add(ComponentsPeer::COMPONENT_ID, $comps->getComponentId());
                    $MRComps = ComponentsPeer::doSelectOne($c);
                    if ($MRComps){
                        $MRComps->setQty4($MRComps->getQty4() + $comps->getQty1() < $MRComps->getQty1()?
                                $MRComps->getQty4() + $comps->getQty1(): $MRComps->getQty1());
                        $MRComps->save();
                    }

                    $c = new Criteria();
                    $c->add(WarehousePeer::COMPONENT_ID, $comps->getComponentId());
                    $warehouse = WarehousePeer::doSelectOne($c);
                    if ($warehouse){
                        $warehouse->setQtyordered($warehouse->getQtyordered() -  $comps->getQty1() > 0?
                                $warehouse->getQtyordered() -  $comps->getQty1(): 0);
                        $warehouse->save();
                    }
                }
            }
        }
    }
    $c =  new Criteria();
    $c->add(ComponentsPeer::COMPONENTGROUP_ID, $MRCompgroupId);
    $compsList = ComponentsPeer::doSelect($c);

    $bComplete = true;
    foreach ($compsList as $comps){
        if ($comps->getQty4() > 0)
                $bComplete = false;
    }
    if ($bComplete)
        $mr->setStatus(CommonValues::$gMRStatus['key']['Completed']);
    $mr->setIsrvresolved(1);
    $mr->save();
}

public function executeView(){
    $this->getResponse()->setTitle('WMS-View-PO');
    $this->po = $this->getPOOrCreate();       
    $this->labels = $this->getLabels();                 
}


public function executePrint(){	
    $this->getResponse()->setTitle('WMS-Print-PO');
    $id = $this->getRequestParameter('id');
    $this->po = POPeer::retrieveByPK($id);
    if (!$this->po) {
        $this->getRequest()->setError('print', 'This PO is not available.');        
        $this->forward('po', 'list');
    }
    if ($this->po->getCompcategory() == CommonValues::$gCompCategory['key']['Main Component']) {
        $mr = MRPeer::retrieveByPK($this->po->getMrno());
    }
    
    if ($this->po->getCompcategory() == CommonValues::$gCompCategory['key']['Sub Component']) {
        $mr = MR2Peer::retrieveByPK($this->po->getMrno());
    }
    
    if ($this->po->getCompcategory() == CommonValues::$gCompCategory['key']['Raw Material']) {
        $mr = MR3Peer::retrieveByPK($this->po->getMrno());
    }    
    
    if (!$mr){
        $this->getRequest()->setError('print', 'This PO is not available.');        
        $this->forward('po', 'list');
    }
    $this->mrno = $mr->getMrno();
    
    $this->supplier = SupplierPeer::retrieveByPK($this->po->getSupplierId());
    
    if (!$this->supplier){
        $this->getRequest()->setError('print', 'This PO is not available.');        
        $this->forward('po', 'list');
    }
    
    //get create user name of object
    $this->CreateName ="";
    $user = sfGuardUserPeer::retrieveByPK($this->po->getUserId());
    if ($user)
        $this->CreateName = $user->getFullname();
    
    $c = new Criteria();
    $c->add(ComponentsPeer::COMPONENTGROUP_ID , $this->po->getComponentgroupId());
    $this->compsList = ComponentsPeer::doSelect($c);
    
    if (!$this->compsList){
        $this->getRequest()->setError('print', 'There is no component in this PO.');        
        $this->forward('po', 'list');
    }
    
    $this->HOSName = '';
    $this->GDName = '';
    $this->HOSSignDate = '';
    $this->GDSignDate = '';
        
    $c = new Criteria();
    $c->add(ApprovalPeer::TYPE , CommonValues::$gApprovalType['key']['PO']);
    $c->add(ApprovalPeer::OBJECT_ID , $id);
    $approvalList = ApprovalPeer::doSelect($c);

    if ($approvalList && count($approvalList) > 0 ){
        foreach ($approvalList as $approval){
            $user = sfGuardUserPeer::retrieveByPK($approval->getUserId());
            if ($user) {
                if ($user->hasGroup('Support Head')) {
                    $this->HOSName = $user->getFullname();
                    $this->HOSSignDate = $approval->getCreatedAt('d/m/Y');
                }
                elseif ($user->hasGroup('General Director')) {
                    $this->GDName = $user->getFullname();
                    $this->GDSignDate = $approval->getCreatedAt('d/m/Y');
                }                          
            }
        }
    }
    $this->HasApproved = false;
    if ($this->HOSName != '' || $this->GDName != '')
        $this->HasApproved = true;    
    
    $c = new Criteria();
    $c->add(MyConfigPeer::IDS, "IDS_PO_CONTACTPERSON");
    $config = MyConfigPeer::doSelectOne($c);

    $this->contactperson = $config->getDescription();

    $c = new Criteria();
    $c->add(MyConfigPeer::IDS, "IDS_PO_DOCUMENTREQUIRE");
    $config = MyConfigPeer::doSelectOne($c);

    $this->docrequire = $config->getDescription();

    $c = new Criteria();
    $c->add(MyConfigPeer::IDS, "IDS_PO_PRINT_TEMPLATE");
    $config = MyConfigPeer::doSelectOne($c);
    if ($config)
        $this->printTemplate = $config->getDescription();
    
}

  protected function addFiltersCriteria($c)
  {
    if (isset($this->filters['pono_is_empty']))
    {
      $criterion = $c->getNewCriterion(POPeer::PONO, '');
      $criterion->addOr($c->getNewCriterion(POPeer::PONO, null, Criteria::ISNULL));
      $c->add($criterion);
    }
    else if (isset($this->filters['pono']) && $this->filters['pono'] !== '')
    {
      $c->add(POPeer::PONO, '%'.strtr($this->filters['pono'], '*', '%').'%', Criteria::LIKE);
    }
    if (isset($this->filters['compcategory_is_empty']))
    {
      $criterion = $c->getNewCriterion(POPeer::COMPCATEGORY, '');
      $criterion->addOr($c->getNewCriterion(POPeer::COMPCATEGORY, null, Criteria::ISNULL));
      $c->add($criterion);
    }
    else if (isset($this->filters['compcategory']) && $this->filters['compcategory'] !== '')
    {
      $c->add(POPeer::COMPCATEGORY, $this->filters['compcategory']);
    }
    if (isset($this->filters['mrno_is_empty']))
    {
      $criterion = $c->getNewCriterion(POPeer::MRNO, '');
      $criterion->addOr($c->getNewCriterion(POPeer::MRNO, null, Criteria::ISNULL));
      $c->add($criterion);
    }
    else if (isset($this->filters['mrno']) && $this->filters['mrno'] !== '')
    {
        $compcategory =null;
        if (isset($this->filters['compcategory']) && $this->filters['compcategory'] !== '')
        {
            $compcategory = $this->filters['compcategory'];
        }
        else
        {
            $compcategory = null;
        }
        if ($compcategory ==null)
        {
            $c->add(POPeer::MRNOREAL, '%'.strtr($this->filters['mrno'], '*', '%').'%', Criteria::LIKE);
        }
        else if ($compcategory == CommonValues::$gCompCategory['key']['Main Component']){            
            $c->add(POPeer::COMPCATEGORY, $compcategory);
            $c->add(MRPeer::MRNO, '%'.strtr($this->filters['mrno'], '*', '%').'%', Criteria::LIKE);
            $c->addJoin(POPeer::MRNO, MRPeer::ID, Criteria::LEFT_JOIN);
        }
        else if ($compcategory == CommonValues::$gCompCategory['key']['Sub Component']){
            $c->add(POPeer::COMPCATEGORY, $compcategory);
            $c->add(MR2Peer::MRNO, '%'.strtr($this->filters['mrno'], '*', '%').'%', Criteria::LIKE);
            $c->addJoin(POPeer::MRNO, MR2Peer::ID, Criteria::LEFT_JOIN);
        }
        else if ($compcategory == CommonValues::$gCompCategory['key']['Raw Material']){
            $c->add(POPeer::COMPCATEGORY, $compcategory);
            $c->add(MR3Peer::MRNO, '%'.strtr($this->filters['mrno'], '*', '%').'%', Criteria::LIKE);
            $c->addJoin(POPeer::MRNO, MR3Peer::ID, Criteria::LEFT_JOIN);
        }        
            

    }
    if (isset($this->filters['category_is_empty']))
    {
      $criterion = $c->getNewCriterion(POPeer::CATEGORY, '');
      $criterion->addOr($c->getNewCriterion(POPeer::CATEGORY, null, Criteria::ISNULL));
      $c->add($criterion);
    }
    else if (isset($this->filters['category']) && $this->filters['category'] !== '')
    {
      $c->add(POPeer::CATEGORY, $this->filters['category']);
    }
    if (isset($this->filters['exparrdate_is_empty']))
    {
      $criterion = $c->getNewCriterion(POPeer::EXPARRDATE, '');
      $criterion->addOr($c->getNewCriterion(POPeer::EXPARRDATE, null, Criteria::ISNULL));
      $c->add($criterion);
    }
    else if (isset($this->filters['exparrdate']))
    {
      if (isset($this->filters['exparrdate']['from']) && $this->filters['exparrdate']['from'] !== '')
      {
        $criterion = $c->getNewCriterion(POPeer::EXPARRDATE, date('Y-m-d', $this->filters['exparrdate']['from']), Criteria::GREATER_EQUAL);
      }
      if (isset($this->filters['exparrdate']['to']) && $this->filters['exparrdate']['to'] !== '')
      {
        if (isset($criterion))
        {
          $criterion->addAnd($c->getNewCriterion(POPeer::EXPARRDATE, date('Y-m-d', $this->filters['exparrdate']['to']), Criteria::LESS_EQUAL));
        }
        else
        {
          $criterion = $c->getNewCriterion(POPeer::EXPARRDATE, date('Y-m-d', $this->filters['exparrdate']['to']), Criteria::LESS_EQUAL);
        }
      }

      if (isset($criterion))
      {
        $c->add($criterion);
      }
    }
    if (isset($this->filters['paymentterm_is_empty']))
    {
      $criterion = $c->getNewCriterion(POPeer::PAYMENTTERM, '');
      $criterion->addOr($c->getNewCriterion(POPeer::PAYMENTTERM, null, Criteria::ISNULL));
      $c->add($criterion);
    }
    else if (isset($this->filters['paymentterm']) && $this->filters['paymentterm'] !== '')
    {
      $c->add(POPeer::PAYMENTTERM, $this->filters['paymentterm']);
    }
    if (isset($this->filters['supplier_id_is_empty']))
    {
      $criterion = $c->getNewCriterion(POPeer::SUPPLIER_ID, '');
      $criterion->addOr($c->getNewCriterion(POPeer::SUPPLIER_ID, null, Criteria::ISNULL));
      $c->add($criterion);
    }
    else if (isset($this->filters['supplier_id']) && $this->filters['supplier_id'] !== '')
    {
      $c->add(POPeer::SUPPLIER_ID, $this->filters['supplier_id']);
    }
    if (isset($this->filters['shippedvia_is_empty']))
    {
      $criterion = $c->getNewCriterion(POPeer::SHIPPEDVIA, '');
      $criterion->addOr($c->getNewCriterion(POPeer::SHIPPEDVIA, null, Criteria::ISNULL));
      $c->add($criterion);
    }
    else if (isset($this->filters['shippedvia']) && $this->filters['shippedvia'] !== '')
    {
      $c->add(POPeer::SHIPPEDVIA, $this->filters['shippedvia']);
    }
    if (isset($this->filters['type_is_empty']))
    {
      $criterion = $c->getNewCriterion(POPeer::TYPE, '');
      $criterion->addOr($c->getNewCriterion(POPeer::TYPE, null, Criteria::ISNULL));
      $c->add($criterion);
    }
    else if (isset($this->filters['type']) && $this->filters['type'] !== '')
    {
      $c->add(POPeer::TYPE, $this->filters['type']);
    }
    if (isset($this->filters['created_at_is_empty']))
    {
      $criterion = $c->getNewCriterion(POPeer::CREATED_AT, '');
      $criterion->addOr($c->getNewCriterion(POPeer::CREATED_AT, null, Criteria::ISNULL));
      $c->add($criterion);
    }
    else if (isset($this->filters['created_at']))
    {
      if (isset($this->filters['created_at']['from']) && $this->filters['created_at']['from'] !== '')
      {
        $criterion = $c->getNewCriterion(POPeer::CREATED_AT, $this->filters['created_at']['from'], Criteria::GREATER_EQUAL);
      }
      if (isset($this->filters['created_at']['to']) && $this->filters['created_at']['to'] !== '')
      {
        if (isset($criterion))
        {
          $criterion->addAnd($c->getNewCriterion(POPeer::CREATED_AT, $this->filters['created_at']['to'], Criteria::LESS_EQUAL));
        }
        else
        {
          $criterion = $c->getNewCriterion(POPeer::CREATED_AT, $this->filters['created_at']['to'], Criteria::LESS_EQUAL);
        }
      }

      if (isset($criterion))
      {
        $c->add($criterion);
      }
    }
    if (isset($this->filters['approvalstatus_is_empty']))
    {
      $criterion = $c->getNewCriterion(POPeer::APPROVALSTATUS, '');
      $criterion->addOr($c->getNewCriterion(POPeer::APPROVALSTATUS, null, Criteria::ISNULL));
      $c->add($criterion);
    }
    else if (isset($this->filters['approvalstatus']) && $this->filters['approvalstatus'] !== '')
    {
      $c->add(POPeer::APPROVALSTATUS, $this->filters['approvalstatus']);
    }
    if (isset($this->filters['receivedstatus_is_empty']))
    {
      $criterion = $c->getNewCriterion(POPeer::RECEIVEDSTATUS, '');
      $criterion->addOr($c->getNewCriterion(POPeer::RECEIVEDSTATUS, null, Criteria::ISNULL));
      $c->add($criterion);
    }
    else if (isset($this->filters['receivedstatus']) && $this->filters['receivedstatus'] !== '')
    {
      $c->add(POPeer::RECEIVEDSTATUS, $this->filters['receivedstatus']);
    }
    else if (isset($this->filters['receivedstatus']) && $this->filters['receivedstatus'] == '')
    {
      //$c->add(POPeer::RECEIVEDSTATUS, CommonValues::$gPOReceivedStatus['key']['Revised'], Criteria::NOT_EQUAL);
    }
  }

    public function executeSLListJobPurchaser(){
        $this->getResponse()->setTitle('WMS-'.$this->getRequestParameter('mod').'-List');
        $this->mod = $this->getRequestParameter('mod');
        switch ($this->mod){
            case 'MR':
        
                    $c = new Criteria();
                    $c->addDescendingOrderByColumn(MRPeer::MRNO);
                    $c->add(MRPeer::APPROVALSTATUS , CommonValues::$gMRApprovalStatus['key']['Approved']);
                    $c->add(MRPeer::STATUS  , CommonValues::$gMRStatus['key']['In progress']);
                    $this->mrList = MRPeer::doSelect($c);
                    break;
                    
            case 'MR2':           
        
                    $c1 = new Criteria();
                    $c1->addDescendingOrderByColumn(MR2Peer::MRNO);
                    $c1->add(MR2Peer::APPROVALSTATUS , CommonValues::$gMRApprovalStatus['key']['Approved']);
                    $c1->add(MR2Peer::STATUS  , CommonValues::$gMRStatus['key']['In progress']);
                    $this->mr2List = MR2Peer::doSelect($c1);
                    break;
                        
            default:            
        
                    $c2 = new Criteria();
                    $c2->addDescendingOrderByColumn(MR3Peer::MRNO);
                    $c2->add(MR3Peer::APPROVALSTATUS , CommonValues::$gMRApprovalStatus['key']['Approved']);
                    $c2->add(MR3Peer::STATUS  , CommonValues::$gMRStatus['key']['In progress']);
                    $this->mr3List = MR3Peer::doSelect($c2);
                    break;
        }
    }
    
    public function executeListWrong()
  {
        $this->getResponse()->setTitle('WMS-Wrong-PO-List');
	$c = new Criteria();
	$polist = POPeer::doSelect($c);
foreach ($polist as $po){

$MRobject = null;
        if ($po->getMrno()) {            
            if ($po->getCompcategory() ==CommonValues::$gCompCategory['key']['Main Component']) 
                $MRobject = MRPeer::retrieveByPK($po->getMrno());
            elseif ($po->getCompcategory() ==CommonValues::$gCompCategory['key']['Sub Component']) 
                $MRobject = MR2Peer::retrieveByPK($po->getMrno());
            else 
                $MRobject = MR3Peer::retrieveByPK($po->getMrno());
            if (!$MRobject){
echo $po->getPono();
echo "<br/>";
            }
       
        }

      }
exit();
}      

public function executeDeleteWrong()
  {
	$c = new Criteria();
	$polist = POPeer::doSelect($c);
foreach ($polist as $po){

$MRobject = null;
        if ($po->getMrno()) {            
            if ($po->getCompcategory() ==CommonValues::$gCompCategory['key']['Main Component']) 
                $MRobject = MRPeer::retrieveByPK($po->getMrno());
            elseif ($po->getCompcategory() ==CommonValues::$gCompCategory['key']['Sub Component']) 
                $MRobject = MR2Peer::retrieveByPK($po->getMrno());
            else 
                $MRobject = MR3Peer::retrieveByPK($po->getMrno());
            if (!$MRobject){
			$po->delete();
            }
       
        }

      }
exit();
}      

  
  public function executeCancel()
  {
      $id = $this->getRequestParameter('id');
      
      $po = POPeer::retrieveByPK($id);
      if (!$po) {          
            $this->getRequest()->setError('edit', 'Could not cancel this PO because it is not available!');        
            $this->forward('po', 'list');
      }
      
        
        $MRId = $po->getMrno();
        $mr = null;
        $compCate =$po->getCompcategory();
        if ($compCate == CommonValues::$gCompCategory['key']['Main Component']) {
            $mr = MRPeer::retrieveByPK($MRId);
        } elseif ($compCate == CommonValues::$gCompCategory['key']['Sub Component']) {
            $mr = MR2Peer::retrieveByPK($MRId);
        } else {
            $mr = MR3Peer::retrieveByPK($MRId);
        }
        
        if (!$mr) { 
            $this->getRequest()->setError('edit', 'Could not cancel this PO because it is not available!');        
            $this->forward('po', 'list');
        }
        
//      $poGrId = $po->getComponentgroupId();
//      $mrGrId = $mr->getComponentgroupId();
//
//      //update warehouse for BOM
//      $c = new Criteria();
//      $c->add(ComponentsPeer::COMPONENTGROUP_ID , $poGrId);
//      $compsList = ComponentsPeer::doSelect($c);
//
//      foreach ($compsList as $comps){
//          $compId = $comps->getComponentId();
//          $c = new Criteria();
//          $c->add(WarehousePeer::COMPONENT_ID , $compId);
//          $warehouse = WarehousePeer::doSelectOne($c);
//          $warehouse = new Warehouse();
//          $warehouse->setQtyordered( $warehouse->getQtyordered() - $comps->getQty1());
//
//          $c = new Criteria();
//          $c->add(ComponentsPeer::COMPONENTGROUP_ID , $mrGrId);
//          $c->add(ComponentsPeer::COMPONENT_ID , $compId);
//          $MRcomps = ComponentsPeer::doSelectOne($c);
//
//          if ($MRcomps->getQty4() < 0 && $MRcomps->getQty4() + $comps->getQty1() > 0){
//              $warehouse->setQtyrequested($warehouse->getQtyrequested() + $MRcomps->getQty4() + $comps->getQty1());
//          }
//          if ($MRcomps->getQty4() > 0) {
//              $warehouse->setQtyrequested($warehouse->getQtyrequested() +  $comps->getQty1());
//          }
//          $MRcomps->setQty4($MRcomps->getQty4() + $comps->getQty1());
//
//          $MRcomps->save();
//          $warehouse->save();
//      }
      
      $po->setReceivedstatus(CommonValues::$gPOReceivedStatus['key']['Cancel']);
      $po->setApprovalstatus(CommonValues::$gMRApprovalStatus['key']['Cancel']);
      $po->save();      
      
      $this->getUser()->setFlash('notice', 'This PO was canceled successfully!');
      $this->redirect('po/list');
  }
  
  public function executeReject()
  {
      $id = $this->getRequestParameter('id');
      $backURL = $this->getRequestParameter('backURL');
      $notes = $this->getRequestParameter('notes');
      
      $po = POPeer::retrieveByPK($id);
      if (!$po) {          
            $this->getUser()->setFlash('notice', 'Could not reject this PO because it is not available!');
            $this->redirect($backURL);
      }
      
        
        $MRId = $po->getMrno();
        $mr = null;
        $compCate =$po->getCompcategory();
        if ($compCate == CommonValues::$gCompCategory['key']['Main Component']) {
            $mr = MRPeer::retrieveByPK($MRId);
        } elseif ($compCate == CommonValues::$gCompCategory['key']['Sub Component']) {
            $mr = MR2Peer::retrieveByPK($MRId);
        } else {
            $mr = MR3Peer::retrieveByPK($MRId);
        }
        
        if (!$mr) { 
            $this->getUser()->setFlash('notice', 'Could not reject this PO because it is not available!');
            $this->redirect($backURL);
        }
        
            
      $po->setReceivedstatus(CommonValues::$gPOReceivedStatus['key']['Cancel']);
      $po->setApprovalstatus(CommonValues::$gMRApprovalStatus['key']['Rejected']);
      $po->setNotes($notes);
      $po->save();
      
      $this->getUser()->setFlash('notice', 'This PO was rejected successfully!');
      $this->redirect($backURL);
  }
    
    public function executePublish()
    {
        $id = $this->getRequestParameter('id');
        
        $po = POPeer::retrieveByPK($id);
        
        if (!$po ){
            $this->getRequest()->setError('publish', 'This PO is not available.');        
            $this->forward('po', 'list');
        }
        
        if ($po->getApprovalstatus() != CommonValues::$gMRApprovalStatus['key']['Initial']) {
            $this->getRequest()->setError('publish', 'This PO was published adready.');        
            $this->forward('po', 'list');            
        }
        
               
        $po->setApprovalstatus(CommonValues::$gMRApprovalStatus['key']['Waiting for approval']);
        $po->setReceivedstatus(CommonValues::$gPOReceivedStatus['key']['In progress']);
        $po->setPublishtime(time());
        
        $po->save();
        
        
        $this->getUser()->setFlash('notice', 'This PO was published successfully.');
        
              
      
        //if this user have permission with PR_APPROVE_MRMAIN
        //then this MR main was consider approved one times
        if ($this->getUser()->hasCredential('APPROVE_PO')){
            $approval = new Approval();
            $approval->setType( CommonValues::$gApprovalType['key']['PO']);
            $approval->setObjectId($po->getId());
            $approval->setUserId($this->getUser()->getGuardUser()->getId());
            $approval->save();          
            
        }        
        
        $this->redirect('po/list?id='.$id);
        
    }
    
    
    
  public function executeDelete()
  {
    $this->po = POPeer::retrieveByPk($this->getRequestParameter('id'));
    $this->forward404Unless($this->po);
    
    if ($this->po->getApprovalstatus() != CommonValues::$gMRApprovalStatus['key']['Initial']
            && !$this->getUser()->hasGroup('Administrator') ){
        $this->getRequest()->setError('delete', 'Could not delete the selected PO. It was published.');
        return $this->forward('po', 'list');
    }

    try
    {
        $PO = $this->po;
                    $c1 = new Criteria();
                    $c1->add(TallyInPeer::TALLYNO, $PO->getId());
                    $c1->add(TallyInPeer::TYPE, CommonValues::$gTallyInType['key']['Supplier']);
                    $TIList = TallyInPeer::doSelect($c1);
                    if ($TIList)
                    {
                        foreach ($TIList as $TI)
                        {
                            $TI->delete();
                        }
                    }
      $this->deletePO($this->po);
    }
    catch (PropelException $e)
    {
      $this->getRequest()->setError('delete', 'Could not delete the selected Po. Make sure it does not have any associated items.');
      return $this->forward('po', 'list');
    }

    return $this->redirect('po/list');
  }
  
  
    public function executeEdit()
  {
    $this->getResponse()->setTitle('WMS-Edit-PO');
    $this->po = $this->getPOOrCreate();

    //revise PO
    $reviseId = $this->getRequestParameter('prepare_revise_Id');
    //Bat dau kiem tra revise
    if ($reviseId != '' && $reviseId != null) {
       $revisePO = POPeer::retrieveByPK($reviseId);
       if (!$revisePO) {
            $this->getRequest()->setError('edit', 'Could not revise this PO because it is not available!');
            $this->forward('po', 'list');
       }
       $this->po = $revisePO->copy();
       $this->po->setReviseId($reviseId);
       $this->po->setReceivedstatus(CommonValues::$gPOReceivedStatus['key']['Initial']);
       $this->po->setApprovalstatus(CommonValues::$gMRApprovalStatus['key']['Initial']);
       $componentGroup = new ComponentGroup();
       $componentGroup->setType(1);
       $componentGroup->save();
       $componentGroupId = $revisePO->getComponentgroupId();
       $c= new Criteria();
       $c->add(ComponentsPeer::COMPONENTGROUP_ID , $componentGroupId);
       $compsList = ComponentsPeer::doSelect($c);
       foreach ($compsList  as $comps) {
           $compsNew = $comps->copy();
           $compsNew->setComponentId($comps->getComponentId());
           $compsNew->setComponentgroupId($componentGroup->getId());
           $compsNew->setQty1($comps->getQty1());
           $compsNew->setQty2($comps->getQty2());
           $compsNew->setQty4($comps->getQty4());
           $compsNew->save();
       }
       $this->po->setComponentgroupId($componentGroup->getId());
       $this->po->save();
    }
    //Ket thuc co kiem tra revise hay khong
    if ($this->po->getApprovalstatus() != CommonValues::$gMRApprovalStatus['key']['Initial']
            && $this->po->getApprovalstatus() != CommonValues::$gMRApprovalStatus['key']['Cancel']
            && $this->po->getApprovalstatus() != CommonValues::$gMRApprovalStatus['key']['Rejected']
            ) {
        $this->getRequest()->setError('edit', 'Cannot edit this PO. It was published.');
        $this->forward('po', 'list');
    }
    
    if ($this->getRequestParameter('mr_id')){
        $this->po->setCategory(MRPeer::retrieveByPK($this->getRequestParameter('mr_id'))->getCategory());
        $this->po->setMrno($this->getRequestParameter('mr_id'));
        $this->po->setCompcategory(CommonValues::$gCompCategory['key']['Main Component']);     
    }
    if ($this->getRequestParameter('mr2_id')){
        $this->po->setCategory(MR2Peer::retrieveByPK($this->getRequestParameter('mr2_id'))->getCategory());
        $this->po->setMrno($this->getRequestParameter('mr2_id'));
        $this->po->setCompcategory(CommonValues::$gCompCategory['key']['Sub Component']);      
    }
    if ($this->getRequestParameter('mr3_id')){
        $this->po->setCategory(MR3Peer::retrieveByPK($this->getRequestParameter('mr3_id'))->getCategory());
        $this->po->setMrno($this->getRequestParameter('mr3_id'));
        $this->po->setCompcategory(CommonValues::$gCompCategory['key']['Raw Material']);      
    }

    if ($this->getRequest()->isMethod('post'))
    {
      $this->updatePOFromRequest();

      $this->po->setTotalprice(CommonValues::CurrencyToNumber($this->po->getTotalprice()));
      $this->po->setSubtotalprice(CommonValues::CurrencyToNumber($this->po->getSubtotalprice()));
      $this->po->setShipandhand(CommonValues::CurrencyToNumber($this->po->getShipandhand()));
      $this->po->setOther(CommonValues::CurrencyToNumber($this->po->getOther()));

      $this->po->setReceivedstatus(CommonValues::$gPOReceivedStatus['key']['Initial']);
      $this->po->setApprovalstatus(CommonValues::$gMRApprovalStatus['key']['Initial']);
      $this->po->setPono(CommonValues::GenerateAutoNumber('PO', $this->po->getPono(), 'PO')); 
      if ($this->po->getCompcategory() == CommonValues::$gCompCategory['key']['Main Component'])
      {
          $this->po->setMrnoreal(MRPeer::retrieveByPK($this->po->getMrno())->getMrno());
      }
      else if ($this->po->getCompcategory() == CommonValues::$gCompCategory['key']['Sub Component'])
      {
            $this->po->setMrnoreal(MR2Peer::retrieveByPK($this->po->getMrno())->getMrno());
      }
      else if ($this->po->getCompcategory() == CommonValues::$gCompCategory['key']['Raw Material'])
      {
          $this->po->setMrnoreal(MR3Peer::retrieveByPK($this->po->getMrno())->getMrno());
      }     
      if ($this->po->getCompcategory() == CommonValues::$gCompCategory['key']['Main Component'])
      {
          $mrmain = MRPeer::retrieveByPK($this->po->getMrno());
          if ($mrmain && $mrmain->getBOM())
          {
              $bom = $mrmain->getBOM();
              $project = $bom->getProject();
              if ($project)
                $this->po->setProjectId($project->getId());
          }
         
          
      }
      
      //Tien code here
      $qtys = $this->getRequestParameter('qtys');
      $unitprices = $this->getRequestParameter('unitprices');
      $totalprices = $this->getRequestParameter('totalprices');
      $rowIds = $this->getRequestParameter('rowIds');
     
      if (isset($rowIds) && count($rowIds) && isset($qtys) && count($qtys) ) {
      	if ($this->po->getComponentgroupId()) {
      	    $c = new Criteria();
      	    $c->add(ComponentsPeer::COMPONENTGROUP_ID , $this->po->getComponentgroupId());
      	    ComponentsPeer::doDelete($c);
      	}
      	$componentGroup = new ComponentGroup();
      	if ($componentGroup)    {
      		$componentGroup->setType(1);
      		$componentGroup->save();
      		$componentGroupId = $componentGroup->getId();
      		
      		if ($componentGroupId) {
      			$this->po->setComponentgroupId($componentGroupId);
      			for($i=0; $i < count($rowIds); $i++){
      			   if (isset($qtys[$i]) && $qtys[$i]) {
      				$components = new Components();
      				if ($components){
      					$components->setComponentgroupId($componentGroupId);
      					$components->setComponentId($rowIds[$i]);
      					$components->setQty1($qtys[$i]);
      					$components->setQty2(CommonValues::CurrencyToNumber($unitprices[$i]));
      					$components->setQty3(CommonValues::CurrencyToNumber($totalprices[$i]));
      					$components->setQty4($qtys[$i]);
      					$components->save();
      				}
      			   }
      			}	      			
      		}
      	}
      }

      
      //add user id
      $this->po->setUserId($this->getUser()->getGuardUser()->getId());        
      try
      {
      	if ($this->getRequestParameter('save_as_approved'))
         {
            $this->po->setReceivedstatus(CommonValues::$gPOReceivedStatus['key']['In progress']);
            $this->po->setApprovalstatus(CommonValues::$gMRApprovalStatus['key']['Approved']);
            $this->po->setPublishtime(time());

            //add approval for PO
            $approval = new Approval();
            $approval->setType( CommonValues::$gApprovalType['key']['PO']);
            $approval->setObjectId($this->po->getId());
            $approval->setUserId(17);//support head
            $approval->save();
            
            $approval = new Approval();
            $approval->setType( CommonValues::$gApprovalType['key']['PO']);
            $approval->setObjectId($this->po->getId());
            $approval->setUserId(16);//general director
            $approval->save();
    		
         }
        $this->savePO($this->po);
      }
      
      catch (PropelException $e)
      {
        $this->getRequest()->setError('edit', 'Could not save the edited Pos.');
        return $this->forward('po', 'list');
      }
     

      $this->getUser()->setFlash('notice', 'Your modifications have been saved');

      
      if ($this->getRequestParameter('save_as_approved'))
         {
            return $this->redirect('po/list');
         }
      else  if ($this->getRequestParameter('save_and_add'))
      {
        return $this->redirect('po/create');
      }
      else if ($this->getRequestParameter('save_and_list'))
      {
        return $this->redirect('po/list');
      }
      else
      {
        return $this->redirect('po/edit?id='.$this->po->getId());
      }
    }
    else
    {
      $this->labels = $this->getLabels();
    }
  }
  
  public function executeList()
  {
      $this->getResponse()->setTitle('WMS-PO-List');
    $this->processSort();

    $this->processFilters();

    $this->filters = $this->getUser()->getAttributeHolder()->getAll('sf_admin/po/filters');

    // pager
    $this->pager = new sfPropelPager('PO', 25);
    $c = new Criteria();
    $c->addDescendingOrderByColumn(POPeer::PONO );
    
    $this->addSortCriteria($c);
    $this->addFiltersCriteria($c);
    $this->pager->setCriteria($c);
    $this->pager->setPage($this->getRequestParameter('page', $this->getUser()->getAttribute('page', 1, 'sf_admin/po')));
    $this->pager->init();
    // save page
    if ($this->getRequestParameter('page')) {
        $this->getUser()->setAttribute('page', $this->getRequestParameter('page'), 'sf_admin/po');
    }
  }
  
  public function handleErrorEdit()
  {
    $this->preExecute();
    $this->po = $this->getPOOrCreate();
     $p = new MR();
   
    $this->updatePOFromRequest();

    $this->labels = $this->getLabels();
    
    //transfer data to edit_form template
    $this->po->qtys = $this->getRequestParameter('qtys');
    $this->po->qtyr = $this->getRequestParameter('qtyr');
    $this->po->unitprices = $this->getRequestParameter('unitprices');
    $this->po->totalprices = $this->getRequestParameter('totalprices');
    $this->po->rowIds = $this->getRequestParameter('rowIds');    

    return sfView::SUCCESS;
  }

    protected function getLabels()
  {
    return array(
      'po{id}' => 'Id:',
      'po{pono}' => 'PO Number:',
      'po{mrno}' => 'MR Number:',
      'po{category}' => 'Category:',
      'po{compcategory}' => 'Compcategory:',
      'po{exparrdate}' => 'Expected Arrival Date:',
      'po{created_at}' => 'Order Date:',
      'po{paymentterm}' => 'Payment Term:',
      'po{supplier_id}' => 'Supplier:',
      'po{shippedvia}' => 'Shipped Via:',
      'po{type}' => 'Type:',
      'po{currency}' => 'Currency:',
      'po{subtotalprice}' => 'Subtotal Price:',
      'po{vat}' => 'Vat %:',
      'po{shipandhand}' => 'Ship & Hand:',
      'po{other}' => 'Other:',
      'po{approvalstatus}' => 'Approval Status:',
      'po{receivedstatus}' => 'Received Status:',
      'po{componentgroup_id}' => 'Component List:',
      'qtys' => 'Component List:',
      'unitprices' => 'Component List:',
      'po{notes}' => 'Notes:',
     
        
    );
  }
}
